#include<time.h>
#include<assert.h>
#include"Protocol.hpp"
#include"Socket.hpp"

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        std::cout<<"错误"<<std::endl;
        return -1;
    }
    
    // 连接服务器
    Sock clientsock;
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);
    clientsock.Socket();
    bool n=clientsock.Connect(serverport,serverip);
    if(n==false){
        std::cout<<"Connect fail"<<std::endl;
        return -1;
    }
    std::cout<<"Connect Success"<<std::endl;
    srand(time(nullptr));
    const string opers="+-*%";
    string buffer_instream;
    while(true)
    {
        cout<<"----------------------------------------------"<<endl;
        int x=rand()%100+1;
        usleep(1234);
        int y=rand()%100;
        usleep(1234);
        char op=opers[rand()%opers.size()];
        Request req(x,y,op);
        string package;
        req.Serialize(&package);
        package=Encode(package);
        std::cout<<"构建了一个请求";
        req.Print_req();
        //客户端向服务器发送请求
        // cout<<package.c_str()<<endl;
        write(clientsock.Fd(),package.c_str(),package.size());
        
        //客户端接收信息
        char buffer[128];
        int n=read(clientsock.Fd(),buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            buffer_instream+=buffer;
            string content;
            bool r=Decode(buffer_instream,&content);
            assert(r);
            Response res;
            r=res.Deserialize(content);
            assert(r);
            std::cout<<"收到了一个回复";
            res.Print_result(); 
        }
         sleep(1);

    }
}